<template>
  <el-dialog title="关联分类" :visible.sync="visible" width="30%">
    <el-popover placement="right-end" v-model="popCatelogSelectVisible">
      <category-cascader :catelogPath.sync="catelogPath"></category-cascader>
      <div style="text-align: right; margin: 0">
        <el-button
          size="mini"
          type="text"
          @click="popCatelogSelectVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="mini" @click="addCatelogSelect"
          >确定</el-button
        >
      </div>
      <el-button slot="reference">新增关联</el-button>
    </el-popover>
    <el-table :data="cateRelationTableData" style="width: 100%">
      <el-table-column prop="id" label="#"></el-table-column>
      <el-table-column prop="brandName" label="品牌名"></el-table-column>
      <el-table-column prop="categoryName" label="分类名"></el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="deleteRelationHandle(scope.row.id)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="visible = false">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import CategoryCascader from "@/views/common/category-cascader";
import RelationApi from "@/api/product/categorybrand";
export default {
  components: { CategoryCascader },
  data() {
    return {
      brandId: null,
      visible: true,
      cateRelationTableData: [],
      popCatelogSelectVisible: false,
      catelogPath: [],
    };
  },
  methods: {
    init(id) {
      this.visible = true;
      if (id) {
        this.brandId = id;
        this.$nextTick(() => {
          this.getRelationData();
        });
      }
    },
    addCatelogSelect() {
      this.popCatelogSelectVisible = false;
      RelationApi.createRelation({
        brandId: this.brandId,
        categoryId: this.catelogPath[this.catelogPath.length - 1],
      }).then(({ data }) => {
        this.getRelationData();
      });
    },
    getRelationData() {
      RelationApi.fetchList({ brandId: this.brandId }).then(({ data }) => {
        this.cateRelationTableData = data;
      });
    },
    deleteRelationHandle(id) {
      RelationApi.deleteRelation({ id }).then(({ data }) => {
        this.getRelationData();
      });
    },
  },
};
</script>
